package cn.iocoder.boot.service.impl.supplier;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.boot.entity.ComponentPrice;
import cn.iocoder.boot.entity.ComponentStock;
import cn.iocoder.boot.enums.SupplierCodeEnum;
import cn.iocoder.boot.service.CallLimitService;
import cn.iocoder.boot.service.ComponentPriceService;
import cn.iocoder.boot.service.ComponentStockService;
import cn.iocoder.boot.service.HttpRequestLogService;
import cn.iocoder.boot.service.impl.SalePriceConfigServiceImpl;
import cn.iocoder.boot.utils.ICEasyEncryptionUtil;
import cn.iocoder.boot.utils.MessageUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@DS("master")
@Slf4j
public class ICEasyServiceImpl {

    @Resource
    private ComponentStockService componentStockService;

    @Resource
    private ComponentPriceService componentPriceService;

    @Resource
    private SalePriceConfigServiceImpl salePriceConfigService;

    @Resource
    private CallLimitService callLimitService;

    @Resource
    private HttpRequestLogService httpRequestLogService;

    private static final String ACCOUNT = "kingbrother";
    private static final String PASSWORD = "Kiy3@da46aKpsfa_uHds";
    private static final String API_URL = "https://www.iceasy.com/external/api/product/kingbrother/ajaxList";

    public List<ComponentPrice> queryOne(String model, Map<String, BigDecimal> componentSupplierMap) {
        try {
            callLimitService.supplierLimitCall(SupplierCodeEnum.ICEAZY.getCode());

            // 构建请求参数
            String txnTime = getCurrentTxnTime();
            Map<String, Object> params = buildRequestParams(model, txnTime);

            // 发送请求并处理响应
            String responseBody = sendPostRequest(params);
            log.info("{} 艾矽易 queryOne API response: {}", model, responseBody);
            return handleSingleResponse(responseBody, componentSupplierMap, model);
        } catch (Exception e) {
            log.error("查询单个组件信息失败，型号: {}", model, e);
            MessageUtil.sentMessage("26827", "艾矽易查询型号异常" + e.getMessage(), "艾矽易查询型号异常");
        }
        return new ArrayList<>();
    }

    public void query(List<String> models, Map<String, BigDecimal> componentSupplierMap) {
        for (String model : models) {
            try {
                queryOne(model, componentSupplierMap);
            } catch (Exception e) {
                log.error("批量查询组件信息失败，型号: {}", model, e);
                MessageUtil.sentMessage("26827", "艾矽易查询型号价格异常" + e.getMessage(), "艾矽易查询型号价格异常");
            }
        }
    }

    /**
     * 构建请求参数
     */
    private Map<String, Object> buildRequestParams(String model, String txnTime) {
        return Map.of(
                "pageIndex", "1",
                "pageSize", "1000",
                "account", ACCOUNT,
                "Key", Objects.requireNonNull(ICEasyEncryptionUtil.encrypt(ACCOUNT, PASSWORD, txnTime)),
                "date", txnTime,
                "keyWord", model
        );
    }

    /**
     * 发送POST请求
     */
    private String sendPostRequest(Map<String, Object> params) {
        try (HttpResponse response = HttpRequest.post(API_URL)
                .contentType("application/x-www-form-urlencoded")
                .form(params)
                .execute()) {
            httpRequestLogService.saveHttpRequestLog(API_URL, "ICEasy_queryOne", params.toString(), response.body(), response.getStatus());
            return response.body();
        } catch (Exception e) {
            log.error("发送HTTP请求失败", e);
            throw new RuntimeException("发送HTTP请求失败", e);
        }
    }

    /**
     * 处理单个查询响应
     */
    private List<ComponentPrice> handleSingleResponse(String responseBody, Map<String, BigDecimal> componentSupplierMap, String model) {
        if (responseBody == null) {
            log.warn("响应内容为空");
            return new ArrayList<>();
        }

        JSONObject jsonResponse = JSONUtil.parseObj(responseBody);
        String code = jsonResponse.getStr("code");
        List<ComponentPrice> componentPriceList = new ArrayList<>();
        if ("100".equals(code)) {
            JSONObject data = jsonResponse.getJSONObject("data");
            if (data == null) {
                return new ArrayList<>();
            }

            JSONArray dataArray = data.getJSONArray("rows");
            for (int i = 0; i < dataArray.size(); i++) {
                JSONObject item = dataArray.getJSONObject(i);
                ComponentPrice componentPrice = processComponentItem(item, componentSupplierMap, model);
                componentPriceList.add(componentPrice);
            }
        } else {
            log.warn("API返回错误代码: {}, 响应内容: {}", code, responseBody);
            MessageUtil.sentMessage("26827", "艾矽易查询型号失败" + responseBody, "艾矽易查询型号失败");
        }
        return componentPriceList;
    }

    /**
     * 处理组件数据项
     */
    private ComponentPrice processComponentItem(JSONObject item, Map<String, BigDecimal> componentSupplierMap, String model) {
        // 处理库存信息
        ComponentStock stock = createComponentStock(item, model);
        componentStockService.saveComponentStockOfUniqueKey(stock);

        // 处理价格信息
        JSONArray resultArray = processPriceInfo(item.getJSONArray("prices"));
        String saleJson = salePriceConfigService.getSaleJson(
                resultArray.toString(), stock.getModel(), "RMB");

        // 创建价格对象
        ComponentPrice componentPrice = createComponentPrice(
                item, stock, resultArray, saleJson, componentSupplierMap, stock.getUniqueId());

        componentPriceService.createComponentPriceOfUniqueKey(componentPrice);
        componentPrice.setStockInfo(stock);
        return componentPrice;
    }

    /**
     * 创建组件库存对象
     */
    private ComponentStock createComponentStock(JSONObject item, String model) {
        ComponentStock stock = new ComponentStock();
        stock.setModel(item.getStr("partNo"));
        stock.setKeyword(model);
        stock.setType(item.getStr("categoryFirst"));
        stock.setGoodsId(item.getStr("sku"));
        stock.setPartnumber(item.getStr("sku"));
        stock.setBrand(item.getStr("linecard"));
        stock.setSpecifications(item.getStr("desc"));
        stock.setStockType(1);
        stock.setSupplierCode(SupplierCodeEnum.ICEAZY.getCode());
        stock.setUniqueId(SupplierCodeEnum.ICEAZY.getCode() + "_" + item.getStr("sku"));
        return stock;
    }

    /**
     * 处理价格信息
     */
    private JSONArray processPriceInfo(JSONArray pricesArray) {
        JSONArray resultArray = new JSONArray();
        if (pricesArray == null) {
            return resultArray;
        }

        for (int i = 0; i < pricesArray.size(); i++) {
            JSONObject priceItem = pricesArray.getJSONObject(i);
            JSONObject priceInfo = new JSONObject();

            priceInfo.put("Price", priceItem.getBigDecimal("price").toString());
            priceInfo.put("Currency", "RMB");
            priceInfo.put("Quantity", priceItem.getInt("qty").toString());

            resultArray.add(priceInfo);
        }
        return resultArray;
    }

    /**
     * 创建组件价格对象
     */
    private ComponentPrice createComponentPrice(JSONObject item, ComponentStock stock,
                                                JSONArray resultArray, String saleJson,
                                                Map<String, BigDecimal> componentSupplierMap,
                                                String uniqueId) {

        return new ComponentPrice(
                uniqueId,
                resultArray.toString(),
                item.getLong("stockNumCn"),
                null,
                item.getStr("packing"),
                "RMB",
                stock.getModel(),
                resultArray.toString(),
                saleJson,
                componentSupplierMap.getOrDefault(SupplierCodeEnum.ICEAZY.getCode(), BigDecimal.valueOf(2))
        );
    }


    /**
     * 获取当前交易时间（可以根据实际需求实现）
     */
    private String getCurrentTxnTime() {
        // 这里可以使用当前时间，格式如：yyyyMMddHHmmss
        // 示例中保留了原有的固定时间，实际应用中应该动态生成
        return "20250425141920";
    }
}
